package com.mike.service.impl;

import com.mike.CodeMapper;
import com.mike.po.AuthCode;
import com.mike.service.CodeService;
import com.mike.service.EmailServiceFeignClient;
import com.mike.utils.CodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.Optional;

/**
 * @Description
 * @Date 2021/11/29 16:53
 * @Created by mike
 */
@Service
public class CodeServiceImpl implements CodeService {

    @Autowired
    private CodeMapper codeMapper;

    @Autowired
    private EmailServiceFeignClient emailClient;

    /**
     * ⽣成验证码并发送到对应邮箱，成功true，失败false
     */
    @Override
    public Boolean createCode(String email) {
        long currentTime = System.currentTimeMillis();
        AuthCode authCode = new AuthCode();
        authCode.setEmail(email);
        Optional<AuthCode> authCodeOptional = codeMapper.findOne(Example.of(authCode));
        if (authCodeOptional.isPresent()){
            authCode = authCodeOptional.get();
            // 时间小于一分钟,不予重复发送
            if ((currentTime -authCode.getCreateTime().getTime()) < 60*1000){
                return false;
            }
        }
        String code = CodeUtils.generateCode();
        authCode.setCode(code);
        authCode.setCreateTime(new Timestamp(currentTime));
        authCode.setExpireTime(new Timestamp(currentTime + 1000 * 60 *10));
        Boolean sendMail = emailClient.sendMail(code, email);
        codeMapper.save(authCode);
        return sendMail;
    }

    /**
     * 校验验证码是否正确，0正确1错误2超时
     */
    @Override
    public Integer validateCode(String email,String code) {
        AuthCode authCode = new AuthCode();
        authCode.setEmail(email);
        authCode.setCode(code);
        Optional<AuthCode> authCodeOptional = codeMapper.findOne(Example.of(authCode));
        if (authCodeOptional.isEmpty()){
            return 1;
        }
        AuthCode authCode1 = authCodeOptional.get();
        long currentTime = System.currentTimeMillis();
        if (currentTime >= authCode1.getCreateTime().getTime() && currentTime <= authCode1.getExpireTime().getTime()){
            return 0;
        }
        return 2;
    }
}
